package com.test.course2;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;


public class ImageServlet extends HttpServlet {
    private Font font = new Font("Courier", Font.BOLD, 12);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get the counter value from the servlet context
        Counter counter = (Counter) getServletContext().getAttribute("counter");
        String count = Integer.toString(counter.getCount());
        counter.add();
        System.out.println("image-count: " + count);
        int len = count.length(); // Number of digits
        BufferedImage image = new BufferedImage(11 * len, 16, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, 11 * len, 16);
        g.setColor(Color.WHITE);
        g.setFont(font);
        char c;
        for (int i = 0; i < len; i++) {
            c = count.charAt(i);
            g.drawString(String.valueOf(c), i * 11 + 1, 12);
            g.drawLine((i + 1) * 11 - 1, 0, (i + 1) * 11 - 1, 16);
        }
        g.dispose();
        response.setContentType("image/jpeg");
        ImageIO.write(image, "jpeg", response.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}